<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
class Template extends \app\admin\controller\Admin{
    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->model=new \app\admin\model\TemplateModel();
        $this->TemplateHistoryModel=new \app\admin\model\TemplateHistoryModel();
        $this->validate=new \app\admin\validate\TemplateValidate();
    }   
    public function index(){
        $where[]=["type","=","index"];
        $data=$this->model->where($where)->order('sort asc,template_id desc')->select();
        View::assign("data",$data);
        return View::fetch();
    }
    //设置状态是否为默认状态
    public function setStatus(){     
        $id=Request::param('id',0,"intval");
        $type=Request::param('type');
        $status=Request::param('status',0,"intval");
        //将之前默认取消掉
        $this->model->where("type",$type)->update(array("isdefault"=>0));   
        //
        $this->model->update(['template_id'=>$id,'isdefault'=>$status]);
        //记录日志
        $this->UserLogModel->add("update",$this->model->getName(),$id);        
        $this->success("设置成功");
    }    
    //更新排序
    public function updateSort(){
        $template_id=Request::param('template_id');
        $sort=Request::param('sort');
        foreach($template_id as $key=>$v){
            $this->model->update(['template_id'=>$template_id[$key],'sort'=>$sort[$key]]);
        }
        $this->success("设置成功");
    }       
    public function list(){      
        $where["type"]="list";
        $data=$this->model->where($where)->order('sort asc,template_id desc')->select();
        View::assign("data",$data);
        return View::fetch("index");
    }    
    public function view(){
        $where["type"]="view";
        $data=$this->model->where($where)->order('sort asc,template_id desc')->select();
        View::assign("data",$data);
        return View::fetch("index");
    }    
    public function search(){
        $where["type"]="search";
        $data=$this->model->where($where)->order('sort asc,template_id desc')->select();
        View::assign("data",$data);
        return View::fetch("search");
    }     
    public function public(){     
        $where["type"]="public";
        $data=$this->model->where($where)->order('sort asc,template_id desc')->select();
        View::assign("data",$data);
        return View::fetch("index");
    }       
    public function add(){
        if(request()->isPost()){
            $data=$this->request->param();
            //变量名是否存在
            if($data['type']=="public"){
                $this->validate->rule['myvar']['unique']='template,myvar';
            }
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }            
            $this->model->save($data);
            $lastId=$this->model->template_id;
            $this->model->makeTemplateFile($lastId);//生成模板文件
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$lastId,$this->request->param());
            $this->success("添加成功");
        }else{
            $type=Request::param('type');
            if(!$type){$this->error("模板类型不明确");}
            View::assign("type",$type);
            return View::fetch();
        }
    }  
    public function update(){        
        if(request()->isPost()){
            $data=$this->request->param();
            //变量名是否存在
            if($data['type']=="public"){
                $this->validate->rule['myvar']['unique']='template,myvar,'.Request::param('template_id',0,"intval");
            }            
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }
            //记录历吏版本
            $this->setHistory($data['template_id'],$data['content']);            
            $this->model->update($data);
            $this->model->makeTemplateFile($data['template_id']);//生成模板文件
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$data['template_id'],$this->request->param());
            $this->success("添加成功");
         
        }else{
            $template_id=Request::param('template_id');
            $r=$this->model->find($template_id);
            View::assign("r",$r);
            return View::fetch();
        }
    }     
    //删除模板
    public function delete(){
        $template_id=Request::param('template_id');
        $template=$this->model->find($template_id)->toArray();
        if($template["isdefault"]){
            $this->error("默认模板禁止删除！");
        }else{
            //删除模板表记录
            $this->model->where("template_id",$template_id)->delete();
            //移到回收站表
            $template["delete_time"]=time();
    
            Db::name("template_recycle")->replace()->insert($template);
            //删除文件
            $this->model->deleteTemplateFile($template_id);
            //
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$template_id,$this->request->param());
            $this->success("删除成功");            
        }
    }
    //记录历吏修改
    private function setHistory($template_id,$new_template){
        //老的模板内容（未修改前的）
        $old_template=$this->model->where("template_id",$template_id)->value("content");
        //如果老的模板内容和新的模板内容一样也不做版本标记
        if($old_template==$new_template){
            return;
        }
        //
        $data["template_id"]=$template_id;
        $data["addtime"]=time();
        $data["userid"]=$this->user_id;
        $data["username"]=$this->username;
        $data["content"]=$old_template;
        $this->TemplateHistoryModel->save($data);
        //查询备份的模板数据是否大于设置的值，多余的删除
        $maxBake=config("app.max_template_bake");
        $count=$this->TemplateHistoryModel->where("template_id",$template_id)->count();
        if($count>$maxBake){
            $min_id=$this->TemplateHistoryModel->where("template_id",$template_id)->min("id");
            $this->TemplateHistoryModel->where("id",$min_id)->delete();
        }
    }
}

